import json
import os
import re
import datetime
from flaskUI.auth import login_required
from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from kubernetes import client, config
import time
import yaml

config.kube_config.load_kube_config(config_file="./kubeconf.yaml")
v1 = client.CoreV1Api()
bp = Blueprint('k8s-show', __name__)

# 配置cors解决资源跨域问题
from flask_cors import CORS 
cors = CORS(bp) 

def transCpu(I):
    if I[-1] == 'm':
        return float(I[:-1])/1000
    return float(I)

def transMemory(I):
    pat = ['Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei']
    for i in range(1, 7):
        if I[-2:] == pat[i-1]:
            return float(I[:-2])*(1024**i)

def getNS():
    ns = []
    rets = v1.list_namespace().items
    for ret in rets:
        ns.append(ret.metadata.name)
    return ns

def getCpuMemInfo():
    nodes = v1.list_node().items
    totalCpu = 0
    totalMemory = 0
    usedCpu = 0
    usedMemory = 0
    for node in nodes:
        cpu = transCpu(node.status.allocatable['cpu'])
        memory = transMemory(node.status.allocatable['memory'])
        totalCpu += cpu
        totalMemory += memory
    pods = v1.list_pod_for_all_namespaces().items
    # print(pods)
    for pod in pods:
        for container in pod.spec.containers:
            if container.resources.limits == None:
                cpu = 0
                memory = 0
            else:
                cpu = transCpu(container.resources.requests['cpu'])
                memory = transMemory(container.resources.requests['memory'])
            usedCpu += cpu
            usedMemory += memory
    return totalCpu, totalMemory, usedCpu, usedMemory

#get the info about cpu and memory of Pod
def get_pod_resource():
    ret = os.popen("kubectl top pods -A").read().split("\n")
    Pod_cpu = {}
    Pod_memory = {}
    for i in range(1, len(ret)-1):
        temp = re.sub(' +', ',', ret[i]).split(',')
        Pod_cpu[temp[1]] = temp[2]
        Pod_memory[temp[1]] = temp[3]
    return Pod_cpu, Pod_memory


#查看node的详细信息
def getNodeInfo(name):
    """
    基本信息：
      名称：docker-desktop
      存活时间：27 days
      标签：beta.kubernetes.io/arch = amd64beta.kubernetes.io/os = linuxkubernetes.io/arch = amd64kubernetes.io/hostname = docker-desktopkubernetes.io/os = linuxnode-role.kubernetes.io/control-plane =node-role.kubernetes.io/master =node.kubernetes.io/exclude-from-external-load-balancers =
      注释：kubeadm.alpha.kubernetes.io/cri-socket = /var/run/dockershim.socknode.alpha.kubernetes.io/ttl = 0volumes.kubernetes.io/controller-managed-attach-detach = true
      查看yaml
    系统信息：
      系统架构：amd64
      操作系统：linux
      操作系统镜像：Docker Desktop
      操作系统内核：4.19.128-microsoft-standard
      容器runtime版本：docker://20.10.13
      kubelet版本：v1.22.5
    已分配资源：
      cpu预留：0.950 core (7%)
      cpu限制：0.000 core (0%)
      内存预留：440 Mi (3%)
      内存限制：340 Mi (2%)
      Pods：13 (12%)
    （可选
    Pods：
    镜像：
    资源信息：
    """
    pods_sum = {}
    rets = v1.list_node().items
    for ret in rets:
        pods_sum[ret.metadata.labels["kubernetes.io/hostname"]] = 0
    rets = v1.list_pod_for_all_namespaces().items
    for ret in rets:
        pods_sum[ret.spec.node_name] += 1
    basicInfo = {}
    systemInfo = {}
    allocatedInfo = {}
    rets = v1.list_node().items
    for ret in rets:
        if ret.metadata.name == name:
            #基本信息
            basicInfo['name'] = name
            basicInfo['live'] = str((datetime.datetime.now().replace(tzinfo=datetime.timezone.utc).__sub__(ret.metadata.creation_timestamp)).days) + " days"
            basicInfo['label'] = []
            for k in ret.metadata.labels:
                basicInfo['label'].append(k + "=" + ret.metadata.labels[k])
            basicInfo['anno'] = []
            for k in ret.metadata.annotations:
                basicInfo['anno'].append(k + "=" + ret.metadata.annotations[k])
            #系统信息
            systemInfo['archi'] =  ret.status.node_info.architecture
            systemInfo['OS'] =  ret.status.node_info.operating_system
            systemInfo['OSimage'] = ret.status.node_info.os_image
            systemInfo['OScore'] = ret.status.node_info.kernel_version
            systemInfo['runtime'] = ret.status.node_info.container_runtime_version
            systemInfo['kubelet'] = ret.status.node_info.kubelet_version
            #已分配资源
            allocatedInfo['cpuAlloc'] = str(ret.status.allocatable['cpu']) + " core"
            allocatedInfo['memAlloc'] = str(round(transMemory(ret.status.allocatable['memory']) / 1024 /1024/1024, 1)) + " Gi"
            allocatedInfo['pods_max'] = ret.status.allocatable['pods']
            allocatedInfo['pods_num'] = pods_sum[name]
            return {"base": basicInfo, 
                    "system": systemInfo, 
                    "allo": allocatedInfo}


# @bp.route('/')
# @login_required
# def index():
#     totalCpu, totalMemory, usedCpu, usedMemory = getCpuMemInfo()
#     print(round(usedMemory/totalMemory, 4))
#     return render_template('k8s-show/index.html', cpu=str(usedCpu*100), memory=str(round(usedMemory *100 /totalMemory, 4)))

# @bp.route('/cluster', methods=('GET', 'POST'))
# @login_required
# def cluster():
#     rets = getNodeInfo()
#     return render_template('k8s-show/cluster.html', posts=rets)

# @bp.route('/namespace', methods=('GET', 'POST'))
# @login_required
# def namespace():
#     res = v1.list_namespace().items
#     rets = []
#     for re in res:
#         rets.append(re.metadata.name)
#     return render_template('k8s-show/namespace.html', posts=rets)

# @bp.route('/service', methods=('GET', 'POST'))
# @login_required
# def service():
#     res = v1.list_service_for_all_namespaces(watch=False).items
#     rets = []
#     for re in res:
#         rets.append({
#             "kind": re.kind,
#             "namespace": re.metadata.namespace,
#             "name": re.metadata.name,
#             "ip": re.spec.cluster_ip,
#             "port": re.spec.ports[0].node_port
#         })
#         print(re.spec.ports[0].node_port)
#     return render_template('k8s-show/service.html', posts=rets)

# @bp.route('/pod', methods=('GET', 'POST'))
# @login_required
# def pod():
#     res = v1.list_pod_for_all_namespaces(watch=False).items
#     rets = []
#     for re in res:
#         rets.append({
#             "ip": re.status.pod_ip,
#             "ns": re.metadata.namespace,
#             "name": re.metadata.name,
#         })

#     return render_template('k8s-show/pod.html', posts=rets)

# @bp.route('/node_yaml/<name>', methods=('GET', 'POST'))
# @login_required
# def node_yaml(name):
#     command = "kubectl get node " + name + " -o yaml"
#     rets = os.popen(command).read()
#     return render_template('k8s-show/yaml.html', name=name, posts=rets)

# @bp.route('/pod_yaml/<name>/<ns>', methods=('GET', 'POST'))
# @login_required
# def pod_yaml(name, ns):
#     # rets = v1.connect_get_namespaced_pod_proxy(name=name, namespace=ns)
#     command = "kubectl get po " + name + " --namespace " + ns + " -o yaml"
#     rets = os.popen(command).read()
#     return render_template('k8s-show/yaml.html', name=name, posts=rets)

# @bp.route('/service_yaml/<name>/<ns>', methods=('GET', 'POST'))
# @login_required
# def service_yaml(name, ns):
#     # rets = v1.connect_get_namespaced_pod_proxy(name=name, namespace=ns)
#     command = "kubectl get service " + name + " --namespace " + ns + " -o yaml"
#     rets = os.popen(command).read()
#     return render_template('k8s-show/yaml.html', name=name, posts=rets)

# @bp.route('/ns_yaml/<name>', methods=('GET', 'POST'))
# @login_required
# def ns_yaml(name):
#     # rets = v1.connect_get_namespaced_pod_proxy(name=name, namespace=ns)
#     command = "kubectl get namespace " + name + " -o yaml"
#     rets = os.popen(command).read()
#     return render_template('k8s-show/yaml.html', name=name, posts=rets)


# @bp.route('/createyaml', methods=('GET', 'POST'))
# @login_required
# def createyaml():

#     return render_template('k8s-show/createyaml.html')


# @bp.route('/getyaml', methods=('GET', 'POST'))
# @login_required
# def getyaml():
#     name = request.args.get("name")
#     data = request.args.get("data")
#     data = data.replace("huanhang", "\n")
#     # print(data)
#     file = open("./storage/yamlcreateservice/" + name + ".yaml", 'w')
#     file.write(data)
#     file.close()
#     data = data.split("\n")
#     for d in data:
#         if d.startswith("kind"):
#             kind = d[6:].lower()
#             break
#     os.system("kubectl apply -f ./storage/yamlcreateservice/" + name + ".yaml")
#     rets = os.popen("kubectl get "+kind).readlines()
#     flag = "Failed"
#     for ret in rets:
#         if ret.startswith(name):
#             flag = "SUCCESS"

#     return render_template('k8s-show/success.html', type="YAML CREATE", flag=flag)




#####################################################
# api
@bp.route('/compute/api/get_pods/')
def get_pod_of_node():
    data = {}
    node = []
    ip = []
    terminal = []
    rets = v1.list_node().items
    for ret in rets:
        node.append(ret.metadata.labels["kubernetes.io/hostname"])
        ip.append(ret.status.addresses[0].address)
        term = {}
        for label in ret.metadata.labels:
            if label.startswith("terminal"):
                device_name = label[9:]
                term_ip, term_mac = [c.split("_")[-1] for c in ret.metadata.labels[label].split("-")]
                term_mac_new = ['', '', ':', '', '', ':', '', '', ':', 
                '', '', ':', '', '', ':', '', '']
                print(term_mac, term_mac_new)
                term_mac_new[0] = term_mac[0]
                term_mac_new[1] = term_mac[1]
                term_mac_new[3] = term_mac[2]
                term_mac_new[4] = term_mac[3]
                term_mac_new[6] = term_mac[4]
                term_mac_new[7] = term_mac[5]
                term_mac_new[9] = term_mac[6]
                term_mac_new[10] = term_mac[7]
                term_mac_new[12] = term_mac[8]
                term_mac_new[13] = term_mac[9]
                term_mac_new[15] = term_mac[10]
                term_mac_new[16] = term_mac[11]
                term_mac_new = ''.join(term_mac_new)
                term[device_name] = {
                    "ip": term_ip,
                    "mac": term_mac_new
                }
        terminal.append(term)
    temp = [[] for i in range(len(node))]
    rets = v1.list_pod_for_all_namespaces().items
    for ret in rets:
        for i in range(len(node)):
            if ret.spec.node_name == node[i]:
                temp[i].append(ret.metadata.name)
    for i in range(len(node)):
        data[node[i]] = {}
        data[node[i]]["ip"] = ip[i]
        data[node[i]]["pods"] = temp[i]
        data[node[i]]["terminal"] = terminal[i]
    return json.dumps(data)

# the usage of cpu and memory among nodes 
@bp.route('/compute/api/getCMU/')
# @login_required
def getCMU():
    # 测试样例数据
    data = [{"name": "docker-desktop",
             "ip": "192.168.65.4",
             "cpu": "2%",
             "memory": "15%"},
            {"name": "node1",
             "ip": "192.168.65.5",
             "cpu": "15%",
             "memory": "25%"},
            ]
    data = []
    rets = v1.list_node().items
    for ret in rets:
        name = ret.metadata.name
        addresses = ret.status.addresses
        for address in addresses:
            if address.type == 'InternalIP':
                ip = address.address
        a = os.popen("kubectl top nodes").read().split("\n")
        for i in range(1, len(a)-1):
            temp = re.sub(' +', ',', a[i]).split(',')
            if temp[0] == name:
                cpu = temp[2]
                memory = temp[4]
        data.append({
            "name": name,
             "ip": ip,
             "cpu": cpu,
             "memory": memory
        })
    
    return json.dumps(data)

#################################################################################

@bp.route('/compute/new/getPodsWithNS/', methods=('GET', 'POST'))
# @login_required
def new_getpodwithns():
    # 测试样例数据
    ns = request.args.get('ns')
    data = [{"name": "myweb-drkxd",
             "ns": "default",
             "status": "1/1",
             "restart": "3",
             "ip": "10.1.0.158",
             "node": "docker-desktop"},
            {"name": "my2048-sbxzq",
             "ns": "default",
             "status": "1/1",
             "restart": "3",
             "ip": "10.1.0.160",
             "node": "docker-desktop"},
            {"name": "mysql-fhgjv",
             "ns": "default",
             "status": "1/1",
             "restart": "3",
             "ip": "10.1.0.156",
             "node": "docker-desktop"},
            ]
    Pod_cpu, Pod_memory = get_pod_resource()
    data = []
    rets = v1.list_pod_for_all_namespaces(watch=False).items
    # print("canshu:", ns)
    for ret in rets:
        restart = 0
        started = 0
        for status in ret.status.container_statuses:
            restart += int(status.restart_count)
            if status.ready == True:
                started += 1
        if ret.metadata.namespace == ns or ns == "all":
            try:
                data.append({
                    "name": ret.metadata.name,
                    "ns": ret.metadata.namespace,
                    "status": str(started) + "/" + str(len(ret.status.container_statuses)),
                    "restart": restart,
                    "ip": ret.status.pod_ip,
                    "cpu": Pod_cpu[ret.metadata.name],
                    "memory": Pod_memory[ret.metadata.name],
                    "node": ret.spec.node_name
                })
            except:
                data.append({
                    "name": ret.metadata.name,
                    "ns": ret.metadata.namespace,
                    "status": str(started) + "/" + str(len(ret.status.container_statuses)),
                    "restart": restart,
                    "ip": ret.status.pod_ip,
                    "cpu": "0m",
                    "memory": "0Mi",
                    "node": ret.spec.node_name
                })
    return json.dumps(data)

@bp.route('/compute/new/getServicesWithNS/', methods=('GET', 'POST'))
# @login_required
def new_getsvcwithns():
    # 测试样例数据
    ns = request.args.get('ns')
    data = [{"name": "myweb",
             "ns": "default",
             "type": "NodePort",
             "ip": "10.110.44.126",
             "target_port": "8080:31001/TCP"},
            {"name": "mysql",
             "ns": "default",
             "type": "NodePort",
             "ip": "10.104.205.73",
             "target_port": "3306:30809/TCP"},
            {"name": "my2048",
             "ns": "default",
             "type": "NodePort",
             "ip": "10.102.218.237",
             "target_port": "80:31007/TCP"},
            ]
    data = []
    rets = v1.list_service_for_all_namespaces(watch=False).items
    for ret in rets:
        if ret.metadata.namespace == ns or "all" == ns: 
            target_port = []
            for port in ret.spec.ports:
                cp = str(port.port) + ":" + str(port.target_port) + "/" + port.protocol
                target_port.append(cp)

            data.append({
                "name": ret.metadata.name,
                "ns": ret.metadata.namespace,
                "type": ret.spec.type,
                "ip": ret.spec.cluster_ip,
                "target_port": ", ".join(target_port)
            })
    return json.dumps(data)


#######################################
# reference
# [1] layui
# -https://www.layuiweb.com/doc/element/layout.html
# -https://github.com/layui/layui
# [2] how to dynamic show page on the right when click the navigation menu on the left
# -https://blog.csdn.net/Yu_luoluo/article/details/99681654
# -https://blog.csdn.net/qq_36746815/article/details/84062516

# new style
@bp.route('/compute/new/base')
# @login_required
def new_test():
    # print("##################")
    # print("GET YOU BRO")
    # print(request.remote_addr)
    # print(time.asctime( time.localtime(time.time()) ))
    # # write the alert code, can do this but not neccesary
    # print("##################")
    return render_template('k8s-show-new/base.html')

@bp.route('/compute/new/overview')
# @login_required
def overview():
    # 测试样例数据
    data = {"name": "k8s-cluster",
            "version": "v1.22.5",
            "cpu-used": "3",
            "cpu-total": "12",
            "cpu-usage": "25%",
            "memory-used": "6",
            "memory-total": "12",
            "memory-usage": "50%",
            "N-nodes": "2",
            "N-namespaces": "4",
            "N-pods": "13",
            "N-services": "5"}
    data["version"] = v1.list_node().items[0].status.node_info.kubelet_version
    a = os.popen("kubectl top nodes").read().split("\n")
    cpu_used = 0
    cpu_total = 0
    cpu_usage = 0
    mem_used = 0
    mem_total = 0
    mem_usage = 0
    rets = v1.list_node().items
    for ret in rets:
        # print(ret.status.allocatable)
        cpu_total += transCpu(ret.status.allocatable["cpu"])
        mem_total += transMemory(ret.status.allocatable["memory"]) / 1024 / 1024 / 1024
    # print(mem_total)
    for i in range(1, len(a)-1):
        temp = re.sub(' +', ',', a[i]).split(',')
        cpu_used += transCpu(temp[1])
        cpu_usage += float(temp[2][:-1])
        mem_used += transMemory(temp[3]) / 1024 / 1024 /1024
        mem_usage += float(temp[4][:-1])
    # cpu_used /= (len(a) - 2)
    # cpu_usage /= (len(a) - 2)
    # cpu_total = cpu_used / cpu_usage * 100
    # mem_used /= (len(a) - 2)
    # mem_usage /= (len(a) - 2)
    # mem_total = mem_used / mem_usage * 100
    cpu_usage = cpu_used / cpu_total * 100
    mem_usage = mem_used / mem_total * 100
    data["cpu-used"] = round(cpu_used, 2)
    data["cpu-total"] = round(cpu_total)
    data["cpu-usage"] = str(round(cpu_usage, 2)) +"%"
    data["memory-used"] = round(mem_used, 2)
    data["memory-total"] = round(mem_total, 2)
    data["memory-usage"] = str(round(mem_usage, 2)) +"%"
    data["N-nodes"] = len(v1.list_node().items)
    data["N-namespaces"] = len(v1.list_namespace().items)
    data["N-pods"] = len(v1.list_pod_for_all_namespaces(watch=False).items)
    data["N-services"] = len(v1.list_service_for_all_namespaces(watch=False).items)
    # print(cpu_usage)
    # print(mem_usage)
    event = []
    rets = v1.list_event_for_all_namespaces().items
    for ret in rets:
        try:
            event.append({
                "reason": ret.reason,
                "namespace": ret.metadata.namespace,
                "message": ret.message,
                "object": ret.involved_object.kind + "/" + ret.involved_object.name,
                "time": str(int((datetime.datetime.now().replace(tzinfo=datetime.timezone.utc) - ret.last_timestamp).total_seconds()/60) % 60) + " mins"
            })
        except Exception as e:
            pass
    data["events"] = event
    return render_template('k8s-show-new/overview.html', posts=data)

@bp.route('/compute/new/Nodes')
# @login_required
def new_node():
    # 测试样例数据
    data = [{"name": "docker-desktop",
             "ip": "192.168.65.4",
             "status": "Ready",
             "role": "control plane, master",
             "cpu": "2%",
             "memory": "15%"},
            {"name": "node1",
             "ip": "192.168.65.5",
             "status": "Ready",
             "role": "node",
             "cpu": "15%",
             "memory": "25%"},
            ]
    data = []
    rets = v1.list_node().items
    for ret in rets:
        name = ret.metadata.name
        addresses = ret.status.addresses
        for address in addresses:
            if address.type == 'InternalIP':
                ip = address.address
        status = ret.status.conditions[-1].type
        role = []
        for label in ret.metadata.labels:
            if label.startswith("node-role.kubernetes.io/"):
                role.append(label[24:])
        role = ", ".join(role)
        a = os.popen("kubectl top nodes").read().split("\n")
        for i in range(1, len(a)-1):
            temp = re.sub(' +', ',', a[i]).split(',')
            if temp[0] == name:
                cpu = temp[2]
                memory = temp[4]
        data.append({
            "name": name,
             "ip": ip,
             "status": status,
             "role": role,
             "cpu": cpu,
             "memory": memory
        })
    
    return render_template('k8s-show-new/nodes.html', posts=data)

@bp.route('/compute/new/Namespaces')
# @login_required
def new_namespace():
    # 测试样例数据
    data = [{"name": "default",
             "tag": "kubernetes.io/metadata.name=default",
             "status": "active"},
            {"name": "kube-node-lease",
             "tag": "kubernetes.io/metadata.name=kube-node-lease",
             "status": "active"},
            {"name": "kube-public",
             "tag": "kubernetes.io/metadata.name=kube-public",
             "status": "active"},
            {"name": "kube-system",
             "tag": "kubernetes.io/metadata.name=kube-system",
             "status": "active"}]
    data = []
    rets = v1.list_namespace().items
    for ret in rets:
        data.append({
            "name": ret.metadata.name,
            "tag": "kubernetes.io/metadata.name=" + ret.metadata.name,
            "status": ret.status.phase
        })

    return render_template('k8s-show-new/namespaces.html', posts=data)


@bp.route('/compute/new/Pods')
# @login_required
def new_pod():
    # 测试样例数据
    ns = getNS()
    data = [{"name": "myweb-drkxd",
             "ns": "default",
             "status": "1/1",
             "restart": "3",
             "ip": "10.1.0.158",
             "node": "docker-desktop"},
            {"name": "my2048-sbxzq",
             "ns": "default",
             "status": "1/1",
             "restart": "3",
             "ip": "10.1.0.160",
             "node": "docker-desktop"},
            {"name": "mysql-fhgjv",
             "ns": "default",
             "status": "1/1",
             "restart": "3",
             "ip": "10.1.0.156",
             "node": "docker-desktop"},
            ]
    
    data = []
    Pod_cpu, Pod_memory = get_pod_resource()
    # print(Pod_cpu, Pod_memory)
    rets = v1.list_pod_for_all_namespaces(watch=False).items
    for ret in rets:
        restart = 0
        started = 0
        for status in ret.status.container_statuses:
            restart += int(status.restart_count)
            if status.ready == True:
                started += 1
        
        try:
            data.append({
                "name": ret.metadata.name,
                "ns": ret.metadata.namespace,
                "status": str(started) + "/" + str(len(ret.status.container_statuses)),
                "restart": restart,
                "ip": ret.status.pod_ip,
                "cpu": Pod_cpu[ret.metadata.name],
                "memory": Pod_memory[ret.metadata.name],
                "node": ret.spec.node_name
            })
        except:
            data.append({
                "name": ret.metadata.name,
                "ns": ret.metadata.namespace,
                "status": str(started) + "/" + str(len(ret.status.container_statuses)),
                "restart": restart,
                "ip": ret.status.pod_ip,
                "cpu": "0m",
                "memory": "0Mi",
                "node": ret.spec.node_name
            })
    return render_template('k8s-show-new/pods.html', posts=data, ns=ns)

@bp.route('/compute/new/Services')
# @login_required
def new_service():
    # 测试样例数据
    ns = getNS()
    data = [{"name": "myweb",
             "ns": "default",
             "type": "NodePort",
             "ip": "10.110.44.126",
             "target_port": "8080:31001/TCP"},
            {"name": "mysql",
             "ns": "default",
             "type": "NodePort",
             "ip": "10.104.205.73",
             "target_port": "3306:30809/TCP"},
            {"name": "my2048",
             "ns": "default",
             "type": "NodePort",
             "ip": "10.102.218.237",
             "target_port": "80:31007/TCP"},
            ]
    data = []
    rets = v1.list_service_for_all_namespaces(watch=False).items
    for ret in rets:
        target_port = []
        for port in ret.spec.ports:
            cp = str(port.port) + ":" + str(port.target_port) + "/" + port.protocol
            target_port.append(cp)

        data.append({
            "name": ret.metadata.name,
            "ns": ret.metadata.namespace,
            "type": ret.spec.type,
            "ip": ret.spec.cluster_ip,
            "target_port": ", ".join(target_port)
        })

    return render_template('k8s-show-new/services.html', posts=data, ns=ns)

@bp.route('/compute/node_yaml_new/<name>', methods=('GET', 'POST'))
# @login_required
def node_yaml_new(name):
    command = "kubectl get node " + name + " -o yaml"
    rets = os.popen(command).read()
    data = {
        "type": "Node",
        "name": name,
        "data": rets
    }
    return render_template('k8s-show-new/yaml.html', name=name, posts=data)

@bp.route('/compute/ns_yaml_new/<name>', methods=('GET', 'POST'))
# @login_required
def ns_yaml_new(name):
    # rets = v1.connect_get_namespaced_pod_proxy(name=name, namespace=ns)
    command = "kubectl get namespace " + name + " -o yaml"
    rets = os.popen(command).read()
    data = {
        "type": "Namespace",
        "name": name,
        "data": rets
    }
    return render_template('k8s-show-new/yaml.html', name=name, posts=data)

@bp.route('/compute/pod_yaml_new/', methods=('GET', 'POST'))
# @login_required
def pod_yaml_new():
    name = request.args.get("name")
    ns = request.args.get("ns")
    # rets = v1.connect_get_namespaced_pod_proxy(name=name, namespace=ns)
    command = "kubectl get po " + name + " --namespace " + ns + " -o yaml"
    rets = os.popen(command).read()
    data = {
        "type": "Pod",
        "name": name,
        "data": rets
    }
    return render_template('k8s-show-new/yaml.html', name=name, posts=data)

@bp.route('/compute/service_yaml_new/', methods=('GET', 'POST'))
# @login_required
def service_yaml_new():
    name = request.args.get("name")
    ns = request.args.get("ns")
    # rets = v1.connect_get_namespaced_pod_proxy(name=name, namespace=ns)
    command = "kubectl get service " + name + " --namespace " + ns + " -o yaml"
    rets = os.popen(command).read()
    data = {
        "type": "Service",
        "name": name,
        "data": rets
    }
    return render_template('k8s-show-new/yaml.html', name=name, posts=data)


@bp.route('/compute/new/createyaml', methods=('GET', 'POST'))
def createyaml():
    with open("./storage/yamlcreateservice/pod-test.yaml", 'r') as f:
        data = f.read()
        # data = yaml.load(f.read(), Loader=yaml.FullLoader)
    f.close()
    return render_template('k8s-show-new/createyaml.html', posts = data)


@bp.route('/compute/new/getyaml', methods=('GET', 'POST'))
def getyaml():
    name = request.args.get("name")
    data = request.args.get("data")
    data = data.replace("huanhang", "\n")
    # print(data)
    file = open("./storage/yamlcreateservice/" + name + ".yaml", 'w')
    file.write(data)
    file.close()
    data = data.split("\n")
    for d in data:
        if d.startswith("kind"):
            kind = d[6:].lower()
            break
    # print("KIND: ", kind)
    os.system("kubectl apply -f ./storage/yamlcreateservice/" + name + ".yaml")
    rets = os.popen("kubectl get "+ kind + " -A" ).readlines()
    flag = "Failed"
    for ret in rets:
        # print(ret)
        # print("********************")
        if name in ret:
            flag = "SUCCESS"
    # print("NAME: ", name)
    return render_template('k8s-show-new/success.html', type="YAML CREATE", flag=flag)


@bp.route('/compute/new/nodeinfo/<name>', methods=('GET', 'POST'))
def nodeInfo(name):
    info = getNodeInfo(name)
    label = [1, 2, 3]
    anno = [1, 2, 3]
    return render_template('k8s-show-new/node_info.html', posts=info, label=label, anno=anno)





